﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using EnvDTE;
using EnvDTE80;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

namespace CoNatural.Data.VisualStudio.AddIn.Helpers {
	// NOTE Using SqlCommandBuilder is not an option since we cannot control the parameters
	internal class CommandBuilder {
		private static readonly string sqlFileTemplate =
@"
-------------------------------------------------------
-- {0}.sql
--
-- Created by {1} with CoNatural Visual Studio AddIn 
-- Created on {2}
------------------------------------------------------- 

{3}

";
		private static readonly string csFileTemplate =
@"
//-------------------------------------------------------
//-- {0}.cs
//--
//-- Created by {1} with CoNatural Visual Studio AddIn 
//-- Created on {2}
//-------------------------------------------------------
 
using System;
using System.Data;
using CoNatural.Data;

namespace {3} {{
	public class {0} : ICommand {{
		public {0}() {{}}

		public string GetScript() {{ 
			return {5}; 
		}}
{4}
	}}
}}
";

		private static readonly string csPropertyTemplate =
@"
		{0}public {1} {2} {{ get; set; }}";

		private ProjectItems rootCollection;
		private string rootPath;
		private string rootNamespace;

		public CommandBuilder(ProjectItems rootCollection, string rootPath, string rootNamespace) {
			this.rootCollection = rootCollection;
			this.rootPath = rootPath;
			this.rootNamespace = rootNamespace;
		}

		private string CreateCsCommandFile(string path, string commandName, string commandNamespace, string mappedProperties, string sqlScript) {
			string csFileText = string.Format(csFileTemplate, commandName, Environment.UserName, DateTime.Now.ToString(),
				commandNamespace, mappedProperties, sqlScript != null ? "\r\n@\"\r\n" + sqlScript + "\"" : "null");
			string csFilePath = Path.Combine(path, commandName + ".cs");
			File.WriteAllText(csFilePath, csFileText);
			return csFilePath;
		}

		public void CreateCommand(string commandName) {
			string collectionPath;
			string commandNamespace;
			ProjectItems collection = ProjectItemHelper.LocateCollection(rootCollection, rootPath, rootNamespace, commandName, out commandName, out commandNamespace, out collectionPath);

			// create just one .cs file with sql script 
			string csFilePath = CreateCsCommandFile(collectionPath, commandName, commandNamespace, string.Empty, string.Empty);
			// add command file to project
			collection.AddFromFile(csFilePath);
		}
	}
}
